#include "httpClient.h"
#include "tokenStorage.h"
#include "loggerFactory.h"
#include "httplib.h"
#include "appException.h"
#include "stringUtils.h"

const char* HttpClient::baseUrl = "/movie/";

log4cpp::Category& HttpClient::logger = LoggerFactory::getLogger("HttpClient");

HttpClient::HttpClient() : needToken(true),success(false)
{
}

HttpClient::~HttpClient()
{
	abortRequest = 1;
}

void HttpClient::get(const char* url)
{
    char buffer[MAX_PATH] = { 0 };
    sprintf_s(buffer, "%s%s", baseUrl, url);
    DECLARE_CLIENT(client)
    ADD_TOKEN_IF(needToken)
    onMessage(client.Get(buffer));
}

void HttpClient::post(const char* url,const String& body)
{
    char buffer[MAX_PATH] = { 0 };
    sprintf_s(buffer, "%s%s", baseUrl, url);
    DECLARE_CLIENT(client)
    ADD_TOKEN_IF(needToken)
    std::string bd = StringUtils::wstring2UTF8(body.c_str(), body.length());
    onMessage(client.Post(buffer, bd, content_type));
}

void HttpClient::put(const char* url, const char* body)
{
    char buffer[MAX_PATH] = { 0 };
    sprintf_s(buffer, "%s%s", baseUrl, url);
    DECLARE_CLIENT(client)
    ADD_TOKEN_IF(needToken)
    onMessage(client.Put(buffer, body, content_type));
}

void HttpClient::contentType(const char* ct)
{
    this->content_type = ct;
}

void HttpClient::cancelToken()
{
    needToken = false;
}

bool HttpClient::requestSuccess()
{
    return success;
}

std::string HttpClient::getErrorMessage() const
{
    return StringUtils::Wstring2string(errorMessage.c_str());
}

const String& HttpClient::getErrorMessageW() const
{
    return errorMessage;
}

const bool HttpClient::canRetry() const
{
    return retry;
}

void HttpClient::onMessage(const httplib::Result& res)
{
    if (res) {
        if (res->status != 200) {
            Char buffer[MAX_PATH] = { 0 };
            swprintf_s(buffer, L"status:%d", res->status);
            errorMessage = buffer;
            success = false;
        }
        else {
            success = true;
        }
    }
    else {
        char buffer[MAX_PATH] = { 0 };
        std::string msg = httplib::to_string(res.error());
        sprintf_s(buffer, "error:%s", msg.c_str());
        errorMessage = StringUtils::String2Wstring(buffer);
        success = false;
        retry = true;
    }
}

